import { Effect, Reducer } from 'umi';
import {
  _getDentity,
  _getApi_authority,
  _getView_authority,
  _addUser,
} from '@/api/addUser';
import { message } from 'antd';
import { IdentityItem, ApiItem, ViewItem } from '@/type/addUser';
import updataState from '@/utils/modelPut';
export interface addUserModelState {
  identityList: IdentityItem[];
  apiList: ApiItem[];
  viewList: ViewItem[];
}
export interface addUserModelType {
  namespace: 'addUser';
  state: addUserModelState;
  effects: {
    GET_IDENTITY: Effect;
    GET_ApiLIST: Effect;
    GET_VIEWLIST: Effect;
    ADD_USER: Effect;
  };
  reducers: {
    save: Reducer<addUserModelState>;
  };
}
const addUserModel: addUserModelType = {
  namespace: 'addUser',
  state: {
    identityList: [],
    apiList: [],
    viewList: [],
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
  effects: {
    //获取用户信息
    *GET_IDENTITY({}, { call, put }) {
      let res = yield call(_getDentity);
      //用户信息获取成功
      if (res.data.code == 1) {
        yield put(updataState('save', { identityList: res.data.data }));
      } else {
        message.error(res.data.msg);
      }
    },
    //获取api权限列表
    *GET_ApiLIST({}, { call, put }) {
      let res = yield call(_getApi_authority);
      //获取成功
      if (res.data.code == 1) {
        yield put(updataState('save', { apiList: res.data.data }));
      } else {
        message.error(res.data.msg);
      }
    },
    //获取view权限列表
    *GET_VIEWLIST({}, { call, put }) {
      let res = yield call(_getView_authority);
      //获取成功
      if (res.data.code == 1) {
        yield put(updataState('save', { viewList: res.data.data }));
      } else {
        message.error(res.data.msg);
      }
    },
    //添加用户
    *ADD_USER({ payload }, { call, put }) {
      let res = yield call(_addUser, payload);
      //获取成功
      if (res.data.code == 1) {
        message.success(res.data.msg);
      } else {
        res.data.msg && message.error(res.data.msg);
        res.data.err &&
          res.data.err.errors.forEach((item: any) => {
            message.error(item.message);
          });
      }
    },
  },
};

export default addUserModel;
